<template>
  <div class="user">
      <el-row>
        <el-col :span="24">
            <el-input placeholder="请输入内容" class="search-input" v-model="query" @keydown.native.enter="initList">
              <el-button slot="append" icon="el-icon-search" @click="initList"></el-button>
            </el-input>
            <el-button type="success" plain @click="addUserVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table class="mt-15" :data="userList" border style="width:100%">   
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="用户状态" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
            <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="showDeleteDialog(scope.row)"></el-button>
            <el-button size="mini" type="warning" plain icon="el-icon-check" @click="showGrantDialog(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
        <el-pagination 
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="1"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">

        </el-pagination>
      </div>
      <!-- 添加用户模态框 -->
      <el-dialog title="添加用户" :visible.sync="addUserVisible">
        <el-form :model="addForm" lable-width="80px" :rules="rules" ref="addUserForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible=false">取消</el-button>
          <el-button type="primary" @click="addUserSubmit('addUserForm')">确认</el-button>
        </div>
      </el-dialog>
      <!-- 编辑用户模态框 -->
      <el-dialog title="编辑用户" :visible.sync="editUserVisible">
        <el-form :model="editForm" lable-width="80px" :rules="rules" ref="editUserForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible=false">取消</el-button>
          <el-button type="primary" @click="editUserSubmit('editUserForm')">确认</el-button>
        </div>
      </el-dialog>
      <!-- 角色分配模态框 -->
      <el-dialog title="分配角色" :visible.sync="disUserVisible">
        <el-form :model="disFrom" label-width="120px">
          <el-form-item label="当前用户：" prop="username">
            <el-tag type="success">{{disFrom.username}}</el-tag>
          </el-form-item>
           <el-form-item label="当前角色：" prop="role_name">
            <el-tag type="warning">{{disFrom.role_name}}</el-tag>
          </el-form-item>
          <el-form-item label="请选择角色：">
            <el-select v-model="roleId" placeholder="请选择角色">
              <el-option v-for="(role,index) in roleList" :key="index" :label="role.roleName" :value="role.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="disUserVisible=false">取消</el-button>
            <el-button type="primary" @click="disUserSubmit()">确认</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import{getUserList,changeUserState,addUser,deleteUser,getUserById,editUser,getRoleList,disUserRole} from "@/api/index.js"
export default {
  data () {
    return{
      userList:[],// 用户列表
      query:'',// 搜索条件
      total:0,// 数据总条数
      pagesize:5,// 每页显示多少条
      pagenum:1,// 当前页码
      addUserVisible:false,//控制添加用户对话框显示隐藏
      // 添加用户对话框信息
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      editUserVisible:false,//控制编辑用户对话框显示隐藏
      //编辑用户对话框信息
      editForm:{
        username:'',
        email:'',
        mobile:'',
        id:0
      },
      disUserVisible:false,//控制角色分配模态框显示隐藏
      //角色分配信息
      disFrom:{},
      //角色列表
      roleList:[],
      //角色ID
      roleId:'',
      //添加表单的用户验证
      rules:{
        username:[{
          required:true,message:'请输入用户名',trigger:'blur'
        }],
        password:[{
          required:true,message:'请输入用户名',trigger:'blur'
        }],
        email:[{
          required:true,message:'请输入邮箱地址',trigger:'blur'
        }]
      },
    }
  },
  created(){
    this.initList()
  },
  methods:{
    //请求数据
    async initList () {
      let{meta,data} = await getUserList({params:{query:this.query,pagenum:this.pagenum,pagesize:this.pagesize}})
      if (meta.status!==200) return this.$message.error({message:meta.msg})
      this.userList=data.users
      this.total=data.total
    },
    //切换条数
    handleSizeChange(val){
      console.log(`当前每页${val}条`);
      this.pagesize=val
      this.initList()
    },
    //切换页码
    handleCurrentChange(val){
      console.log(`当前处于${val}页`);
      this.pagenum=val
      this.initList()
    },
    //改变用户状态
    async changeState(row){
      console.log(row);
      let{meta,data} = await changeUserState({uid:row.id,type:row.mg_state})
      if(meta.status!==200) return this.$message.warning({message:meta.msg})
      this.$message.success({message:'修改用户状态成功'})
    },
    //用户添加
    addUserSubmit(formName){
      this.$refs[formName].validate(valide =>{
        if(valide){
          //执行添加
          addUser(this.addForm).then(res =>{
            console.log(res)
            if(res.meta.status === 201){
              this.$message.success({message:'添加用户成功'})
            }
            this.addUserVisible = false
            this.initList()
          })
        }
      })
    },
    //通过id获取编辑用户的信息
    async showEditDialog(row){
      this.editUserVisible=true
      //获取用户信息
      let {data,meta} =  await getUserById(row.id)
      if(meta.status!==200) return this.$message.error({message:meta.msg})
      this.editForm.username=data.username
      this.editForm.email=data.email
      this.editForm.mobile=data.mobile
      this.editForm.id=data.id
    },
    //编辑用户
    async editUserSubmit(formName){
      this.$refs[formName].validate(valide=>{
        if(valide)[
          editUser(this.editForm).then(res=>{
            if(res.meta.status===200){
              this.$message.success({message:'修改成功'})
              this.editUserVisible = false
              this.initList()
            }
          })
        ]
      })
    },
    //删除用户
    async showDeleteDialog(row){
      let flog = await this.$confirm('此操作将永久删除该用户，是否确定?','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).catch(()=>{})
      if(!flog) return this.$message.info({message:'已取消删除'}) 
      let {data,meta} = await deleteUser(row.id)
      if(meta.status!==200) return this.$message.error({message:meta.msg})
      this.$message.success({message:'删除成功'})
      this.initList()
    },
    //显示分配角色模态框
    async showGrantDialog(row){
      this.disFrom=row
      this.disUserVisible=true
      let {meta,data} = await getRoleList() 
      if(meta.status===200) return this.roleList = data
    },
    //角色分配
    async disUserSubmit(){
      //当没有选择角色时不做处理
      if(!this.roleId) return this.$message.error({message:'角色不能为空，请选择！'})
      let {meta,data} = await disUserRole({id:this.disFrom.id,rid:this.roleId})
      if(meta.status!==200) return this.$message.error({message:meta.msg})
      console.log(meta);
      this.$message.success({message:'设置角色成功'})
      this.disUserVisible=false
    }
  }
}
</script>

<style lang="less" scoped>
//面包屑样式
.el-breadcrumb {
    background-color: #D3DCE6;
    height: 45px;
    font-size: 15px;
    padding-left: 10px;
    line-height: 45px;
    margin-bottom: 15px;
}
//组件内部style样式
.user{
  .margin-20{
    margin:20px 0;
  }
  .search-input{
    width: 300px;
  }
  .page{
    padding: 5px 0;
    background-color: #D3DCE6;
  }
}
</style>